var lat , lon , zoom=12;
var latAux , lonAux , zoomAux=12;
var chatId="__activity";
var chatNick="__";
var chatNickAux, chatIdAux;
var cont=0;
var map,mapH,mapW;
var geocoder;// = new google.maps.Geocoder();
var deviceId=-2;

var activitiesReady=false;
var configReady=false;

var createEvent=false;

var currPage=null;

var labelClick=false;

//var jf=false;	
//var url;//="https://sites.google.com/site/tucanalmovil/url/url.txt";	
//var url="http://findme2.cloudfoundry.com/devices/";
//var url="http://192.168.43.200:8181/tucanalmovil/devices/";

//var host="https://127.0.0.1:8443";
//var host="https://192.168.43.200:8443";
//var host="https://192.168.2.109:8443";
var host="https://findMe2.cfapps.io";

var  url="/devices/";
var  loginUrl="/ajaxLogin/";
//var url="http://127.0.0.1:8181/tucanalmovil/devices/";
//var url="http://192.168.194.1:8181/tucanalmovil/devices/";
//var url="http://127.0.0.1:8181/tucanalmovil/devices/";
//var url="http://192.168.2.198:8181/tucanalmovil/devices/";
//var url="http://192.168.2.103:8181/tucanalmovil/devices/";

//var url="http://172.16.14.3:8181/tucanalmovil/devices/";
//var url="http://192.168.0.193:8181/tucanalmovil/devices/";

var config;

var refreshTimeout=false;

var watchChat;
var watchGPS;

    function getip(json){
      deviceId=json.ip; 
    }
    
    function getUrl(){ 
    	return host + url;
    }
      
    function getLoginUrl(){ 
    	return host + loginUrl;
    }   
    
    function urlJSONP(json){
    	
        url=json.url; 
        loginUrl=json.loginUrl; 
        host=json.host;
    	//alert(host + url);
    }

var markersArray = [];


var labelsArray = [];

var circlesArray = [];

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }

  if (circlesArray) {
	    for (j in circlesArray) {
	    	circlesArray[j].setMap(null);
	    }
  }  


 if (labelsArray) {
	    for (j in labelsArray) {
	    	labelsArray[j].setMap(null);
	    }
  }  
 
 	
  $("li.botones:not(.mapAll)").remove();
  
}


function paintLabels() {
 if (labelsArray) {
	    for (j in labelsArray) {
	    	labelsArray[j].open();
	    }
  }  
}


function LongPress(map, length) {
  this.length_ = length;
  var me = this;
  me.map_ = map;
  me.timeoutId_ = null;
  google.maps.event.addListener(map, 'mousedown', function(e) {
    me.onMouseDown_(e);
  });
  google.maps.event.addListener(map, 'mouseup', function(e) {
    me.onMouseUp_(e);
  });
  google.maps.event.addListener(map, 'drag', function(e) {
    me.onMapDrag_(e);
  });
};
LongPress.prototype.onMouseUp_ = function(e) {
  clearTimeout(this.timeoutId_);
};
LongPress.prototype.onMouseDown_ = function(e) {
  clearTimeout(this.timeoutId_);
  var map = this.map_;
  var event = e;
  this.timeoutId_ = setTimeout(function() {
    google.maps.event.trigger(map, 'longpress', event);
  }, this.length_);
};
LongPress.prototype.onMapDrag_ = function(e) {
  clearTimeout(this.timeoutId_);
};




function initMap() { 


		if(querystring("lat").length>0) lat=querystring("lat")[0];
		if(querystring("lon").length>0) lon=querystring("lon")[0];
		if(querystring("lat").length>0 && querystring("zoom").length>0) zoom=parseInt(querystring("zoom")[0]);
		if(querystring("lat").length>0 && querystring("idSeg").length>0) idSeguimiento=querystring("idSeg");
		//alert("init map " + lat );
		
		
		
        var mapOptions = {
          center: new google.maps.LatLng(lat,lon),
          zoom: 1,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          zoomControl: true,
          zoomControlOptions: {
              style: google.maps.ZoomControlStyle.LARGE,
              position: google.maps.ControlPosition.LEFT_CENTER
          },
        };

        map = new google.maps.Map(document.getElementById("map_canvas"),     mapOptions);


//norte 37.875192,-4.765127
//este 37.871161,-4.762491
//sur 37.868298,-4.766353
//oeste 37.873625,-4.770105


//  var imageBounds = new google.maps.LatLngBounds(
//      new google.maps.LatLng(37.868598,-4.769905),
//      new google.maps.LatLng(37.875292,-4.762591));
//      //new google.maps.LatLng(40.712216,-74.22655),
//      //new google.maps.LatLng(40.773941,-74.12544));
//
//
//  var feria = new google.maps.GroundOverlay('https://com-ficv-findme.googlecode.com/files/plano.png',imageBounds, {opacity: 0.5});
//  	feria.setMap(map);


	google.maps.event.addListener(map, 'idle', function() {
	

		google.maps.event.clearListeners(map, 'idle');

		$(map_canvas).toggle();

		$(map_canvas).width(mapW);
		$(map_canvas).height(mapH);

		google.maps.event.trigger(map, 'resize');
		
//		if(!lat || lat==null || lat=="undefined") {
//
//			alert(config.lat);
//			lat=config.lat;
//			lon=config.lon;
//			
//		}
		
		
		map.setZoom(zoom); 
		map.setCenter(new google.maps.LatLng(lat, lon));

	
		
		if(password!=null)  getPeople(true);
		

//		$.mobile.changePage($('#page1')); 
//		onBtn();
		
		  var homeControlDiv = document.createElement('div');
		  var homeControl = new HomeControl(homeControlDiv, map);

		  homeControlDiv.index = 1;
		  map.controls[google.maps.ControlPosition.TOP_LEFT].push(homeControlDiv);  

		  
        });

	map.setZoom(5);
	$(map_canvas).toggle();

	  google.maps.event.addListener(map, 'click', function(event) { 
		    if(editMode) { 
		    	prepareMapClick(event.latLng);
		    	editMode=!editMode;
		    	controlText.innerHTML = '<strong>' + $.i18n._('create_event') + '</strong>';
		    }
		  });
	  
//	  
//	  google.maps.event.addListener(map, 'center_changed', function() {
//		  	alert(lat);
//		  	lat=map.getCenter().lat();
//		  	lon=map.getCenter().lng();
//		  	alert(lat);
//		  });
//	  
	  google.maps.event.addListener(map, 'zoom_changed', function() {
		  	zoom=map.getZoom();
		  });

    new LongPress(map, 1250);
    google.maps.event.addListener(map, 'longpress', function(e) {
	if(idSeguimiento!=null) {
		idSeguimiento=null;	
	    alert("Seguimiento abortado");
	}	
    });
    
    //alert(lat + idSeguimiento + queryString("idSeg"));
    //if(idSeguimiento!=null) getPeople();
	  
//alert("go");
//	  goMap();
	  //refreshMap();

        
}
	
function openInfoIndex(i,j) {

	refreshTimeout=true; 
	clearTimeout(peopleWatchID);
						
	markersArray[i]['infowindow'].open(map,markersArray[i]);
	labelsArray[j].close();

	refreshTimeout=false;
	peopleWatchID=setTimeout(function(){getPeople(true)},12000);

}

function getPrecisionColor(precision,offset) {
		
	if(precision<200 && offset < 3600000 ) return "black";
	else return "red";
}

function addMarker(marker) {
//	  var marker = new google.maps.Marker({
//	    position: location,
//	    map: map
//	  });

	  
	    var infoBubble2 = new InfoBubble({
	        map: map,
	        content: '<div class="phoneytext"><a style="text-decoration: none; color: ' + getContrastYIQ(marker.color) + ';"  href="javascript:openInfoIndex(' + marker.index + ',' + labelsArray.length + ')">' + marker.title.substring(0,10) + '</a></div>',
	     //   content: 'hola dsafanombre',
	        position: marker.position,
	        //shadowStyle: 1,
	        padding: 0,	        
	        minHeight: 'auto',
	        minWidth: 'auto',
	        maxHeight: 'auto',
	        maxWidth: 'auto',	        
	        backgroundColor: getRGBA(marker.color),
	        borderRadius: 10,
	        arrowSize: 20,
	        borderWidth: 1,
	        borderColor: getPrecisionColor(marker.precision,marker.offset),
	        disableAutoPan: true,
	        hideCloseButton: false,
	        arrowPosition: 20,
	        backgroundClassName: 'phoney',
	        arrowStyle: 2,
	        overflow: 'hidden',

	      });
	  
//		var infowindow = new google.maps.InfoWindow({
//            content: 
//            '<div style="color:black;">... hace ' + deviceId + '</div>' //+
//
//        });

	    marker['infowindow'].labelIndex=labelsArray.length;
	    labelsArray.push(infoBubble2);
	    
	    
//	    alert("open");
	    
		//infowindow.open(map, marker);
		
		//google.maps.event.trigger( marker, 'click' );
		
	  
	}


var people;
//var paint=true;

function getPeople(paint) {

//	getPosition();

	var d=new Date();	
	clearTimeout(peopleWatchID);
    doAjax({
      	 url: getUrl() + "peopleAround",
      	 type: 'POST',
      	 data:{  deviceId:  deviceId,
      		 	activity: $(selectmenu1).val(), 
      		 	mode: "0.1.11", 
      		 	df:  d.getTime()
      	 },
      	 success: function(data){ 	


			if(idSeguimiento!=null) peopleWatchID=setTimeout(function(){getPeople(true)},config.refresh);

			if(!refreshTimeout) {
				//getEvents();
				people=data;
				//paint=true;
				clearOverlays();
				//$("#botones li:not(.mapAll)").remove();
				if(map && map!=null && $.mobile.activePage.is("#page2")) { 
					getMarkers(data, paint);
				}
				
				else getMarkers(data, false);  
				
			//$( "#mypanel" ).trigger( "updatelayout" );
			}


		},
			

           error: function (jqXHR, textStatus,  errorThrown)  { 
        	   alert("No se ha podido obtener datos de usuarios");
        	  }
           

          });
//	$.getJSON(getUrl() + "peopleAround?deviceId=" + deviceId + "&activity=" + $(selectmenu1).val() + "&mode=0.1.11&df=" + d.getTime(),
//		 
//	});
	
}









function showAlert(title, msg) {
	
if(navigator && navigator.notification) navigator.notification.alert(msg, //mensaje
	function() {
		//$.mobile.changePage($('#page1')); 
		//google.maps.event.trigger(map, 'resize');
	
	}, //funcion callback

	title, //título

	'Ok' // nombre del botón	

	);

else alert(msg);

}

function onDeviceReady() {


	
	if (window.device) { 
		deviceId=device.uuid;
		//deviceId=10;
	} 

//	alert(jf.getTelephoneNumber());
//	alert(jf.getImei());
//	alert(jf.getWords());
//	alert(jf.getTxt());
	
	document.addEventListener("pause", onPause, false);
	document.addEventListener("resume", onResume, false);
	document.addEventListener("backbutton", onBackKeyDown, false);
    //document.addEventListener("menubutton", onMenuKeyDown, false);

//	alert(deviceId);
//	alert(navigator.connection.type);
//	
//	if(navigator && navigator.connection && navigator.connection.type==0) {
//		alert("Es necesaria una conexión de datos. Actívela y reinicie la applicación"); 
//		salirApp();
//	}

    //inicio("0","0", "-1");	
	


	window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, onFSError);
	$("#onButton").trigger("myDeviceReady");
	
//	if (window.device && device.platform=="Android" && parseInt(device.version) < 3){
//	    touchScroll($('.scrollList'))
//	}



}


function getPosition() {

	navigator.geolocation.getCurrentPosition(posSuccess, posError,{maximumAge: 600000, timeout: 5000 });

}

function touchScroll(selector){
    var scrollStartPos = 0;
    $(selector).live('touchstart', function(event) {
      event.preventDefault();
      scrollStartPos = this.scrollTop + event.originalEvent.touches[0].pageY;
    });
    $(selector).live('touchmove', function(event) {
      event.preventDefault();
      this.scrollTop = scrollStartPos - event.originalEvent.touches[0].pageY;
    });
}



var watchID="OFF";
var peopleWatchID;

// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);

// PhoneGap is ready
//



function posSuccess(position) {
	

	if(googleOn) geocoder.geocode({'latLng': new  google.maps.LatLng(position.coords.latitude,position.coords.longitude)}, makeGeocode(position.coords.longitude,position.coords.latitude,position.coords.accuracy));
	else {
		
		var posicion = {"lon":position.coords.longitude,"lat":position.coords.latitude,"acu":position.coords.accuracy};
		if(password==null) getNFm(posicion);
		else inicio(position.coords.longitude,position.coords.latitude,position.coords.accuracy,"N/D","N/D","N/D","N/D","N/D","N/D","N/D","N/D");
	}
	//	inicio(position.coords.longitude,position.coords.latitude,position.coords.accuracy,"N/D","N/D","N/D","N/D","N/D","N/D","N/D","N/D");
	//	inicio(position.coords.longitude,position.coords.latitude,position.coords.accuracy);
}

function makeGeocode(lon,lat,acu) {
    var geocodeCallBack = function(results, status) {
    	
    	
    	
		var calle="N/D";
		var barrio="N/D";
		var distrito="N/D";
		var poblacion="N/D";
		var provincia="N/D";
		var region="N/D";
		var pais="N/D";
		var cp="N/D";
		
		
		if (status == google.maps.GeocoderStatus.OK) {

			   for(j=0;j<results.length;j++) {
				 
				   if(results[j].types[0]=="street_address") calle=results[j].address_components[1].short_name;
				   else if(results[j].types[0]=="neighborhood") barrio=results[j].address_components[0].short_name;
				   else if(results[j].types[0]=="sublocality") distrito= results[j].address_components[0].short_name;
				   else if(results[j].types[0]=="postal_code") {
					   cp= results[j].address_components[0].short_name 
					   poblacion= results[j].address_components[1].short_name ;
				   }
					
			   
			   }
		}
		
		var posicion={	"lon":lon,"lat":lat,"acu":acu,
				"calle":calle,"barrio":barrio,
				"distrito":distrito,"poblacion":poblacion,
				"provincia":provincia,"region":region,
				"pais":pais,"cp":cp
			};

		if(password==null) getNFm(posicion);
		else inicio(lon,lat,acu,calle,barrio,distrito,poblacion,provincia,region,pais,cp);
    }
    
    return geocodeCallBack;
}


function posError(error) {
	
		var msg="No ha sido posible determinar su posición de forma automática. ";
		if(!jf) msg = msg + "Acepte la geolocalización por red en su navegador si desea ser localizado";
		else if(password==null) msg= msg + "Para obtener su número Findme elíjala de forma manual.";	
		else msg= msg + "Si no quiere activar el gps puede activar en la misma pantalla de ajustes la localización por red (más rápida y menor consumo de batería), para que cada vez que entre a la aplicación le ubique orientativamente";
		alert(msg);
	
		if(password==null) choosePositionOnMap();
		else inicio("0","0", "-1","N/D","N/D","N/D","N/D","N/D","N/D","N/D","N/D");

}

function choosePositionOnMap() {

	
		zoom=3;
		lat=0.000001;
		lon=0.000001; 
		initMap();refreshMap();
		prepareFirstPositionClick(new google.maps.LatLng(lat, lon));


		//goPage('page2',true);
}

	


function inicio(lon,lat,acu,calle,barrio,distrito,poblacion,provincia,region,pais,cp) {

	getInit(lon,lat,acu,calle,barrio,distrito,poblacion,provincia,region,pais,cp);

//	if(config!=null) { 
//		//setConfig();
//	} else {
//		showAlert("Aviso",$.i18n._('no_config'));
//		//salirApp();
//	}
	
}

function setConfig() {


	//google.maps.event.addDomListener(window, 'load', initMap);
	


	$("#headerLoading").text("FindMe");

	$('#selectmenu1').val(config.activity);

	var nFm=deviceId;
		

	if(nFm.length>3) nFm=deviceId.substr(0,3) + "-" + deviceId.substr(3);
	$('#nFm').text(nFm);
	
	$('#textinput1').val(config.nick);
	$('#textinput2').val(config.comment);
	$("#latency").val(parseInt(config.latency)/60000);
	$("#refresh").val(parseInt(config.refresh)/1000);
	$("#telefono").val(config.telefono);
	$("#radio").val(config.radioKm);
	
	$('#selectmenu1').selectmenu();
	
	$('#selectmenu1').selectmenu('refresh', true);
	

	var iniMap=false;


	if(googleOn && (!map || map==null))  {

		lat=config.lat;
		lon=config.lon;
		zoom=12;
		initMap();refreshMap();
		iniMap=true;
	}
	
	
	
	
//	if(hayMsg) {
//		$.mobile.changePage($('#pageContactos')); 				
//	} else
	

	if(!iniMap) {
		if(config.nick=="Newbie!!!") {
			alert("Por favor, revisa la configuración e intenta cambiar el nombre por defecto");
			$.mobile.changePage($('#page10')); 
			
		} else 	{
//
//			showContacts();
		}
	} 
	
	$('#page1_fullExtent').text($.i18n._('page1_fullExtent2',[$('#selectmenu1 option:selected').text()]));	
		

	showContacts();
	

	//onBtn();
	
	//if(config.online="on") { 
	//	onBtn();
		//$("#offButton").fadeToggle(1500);
	//} else {
		//$("#offButton").hide();
		//$("#onButton").fadeIn(1500);
	//}
	
	

	
}


function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function doRefreshTimeout() {
	
	if(refreshTimeout) {
		clearTimeout(peopleWatchID);
		peopleWatchID=setTimeout(function(){getPeople(true)},config.refresh);
		refreshTimeout=false;
	}
}


var lastPeticionId=-1;


var googleOn=false;

$(document).ready(function() { 
	

	if(!jf)	readyInit();
	
	$("#onButton").bind("myDeviceReady", function(){
		readyInit();
	 });

});


var password=null;

function getLoginInfo() {
	

//	var k="token";
//	var a = sjcl.json.encrypt(k, "lamiacontraseña");
//	alert(sjcl.json.decrypt(k,a));	
	

	
	
	if(!jf) {
		$("#onButton").trigger("loginReady");
		password="yetlogged";
		return;
	}



	doReadFile();




	
	if(password!=null) {
//		
//		if(googleOn) { initMap();
//		
//		}


		
		
	    doAjax({
	      	 url:  getLoginUrl() + 'post',
	      	type: 'POST',
	      	datatype: 'json',
	      	data:{ 	username: deviceId,
	      			password: password
	      		},
	      	 success: function(data, textStatus, request){

//	            alert(request.getAllResponseHeaders());
	      		//alert("Login success " +  data + textStatus + request);
	      		//alert($.cookie('JSESSIONID',{ Path: '/tucanalmovil', domain: '127.0.0.1'}));
//	      		alert(readCookie('JSESSIONID'));
	      		$("#onButton").trigger("loginReady");

	      		

	      		      
	      	 },
	           error: function (jqXHR, textStatus,  errorThrown) { 
	        	   alert("post login failed " + textStatus + errorThrown)
	       		alert(deviceId);
	       		alert(getLoginUrl());
	           },
	      	 async:   true
	          });

	} else {


		if(googleOn) {
			getPosition();
		} else {
			goMap();
			alert("Bienvenido a FindMe! A continuación intentaremos localizar tu posición para centralizar tus búsquedas");
		}	
		//posError("sinpos");
	}

}	


function goMap() {
	

	if(googleOn) {
		goPage('page2',true);
		//$.mobile.changePage($('#page2'));
	} else {
		if(lat==null || lat=="null") {
			if(config!=null) {
				lat=config.lat;
				lon=config.lon;
			}
				
		}
	
		var d=new Date();
		window.open("app.html?lat=" + lat + "&lon=" + lon + "&zoom=" + zoom + "&idSeg=" + idSeguimiento + "&df=" + d.getTime() ,'_self');

	}

	
}
	
function getNFm(position) {
	callGetCountryCode(position);
}

function callGetNFm(position) {



	
	position.username=deviceId;
	doAjax({
	      	 url:  getLoginUrl() + 'getNFm',
	      	type: 'POST',
	      	datatype: 'json',
	      	data: position,
			//{ 	username: deviceId
	      		//},
	      	 success: function(data, textStatus, request){
	      		 deviceId=data.username;
	      		 if(!data.loggedIn) {
	      			 alert(data.pwd);
	      			 password=null;
	      		 } else {
	      			 password=data.pwd;
	      		 }
	      		//$("#onButton").trigger("loginReady");
		    	if(infoBubble) infoBubble.close();
		    	if(marker) {
		    		marker.setMap(null);
		    		marker=null;
		    	}

		    	
		    	
			    if(password!=null) {
			    	
					doAppendFile();
					
					//sendSMS();	alert("getNFm");
					getComboActivities(true);
			    } else {
			    	alert("No es posible asignar un nFm");
			   
			    }
			    
		    
	      	 },
	           error: function (jqXHR, textStatus,  errorThrown) { alert("Login failed " + textStatus + errorThrown)},
	      	 async:   true
	          });	
	
}


function sendSMS() {
	if(jf) window.sms('668868055', 
	    '__findMeCode:' + deviceId, 
	    function () { 
	       alert('Message sent successfully');  
	    },
	    function (e) {
		alert('Message Failed:' + e);
	    }
	);
}

function callGetCountryCode(position) {


	position.username="findme";
	position.type="json";
	position.lng=position.lon;


	doAjax({
	      	 url:  'http://api.geonames.org/countryCode',
	      	type: 'POST',
	      	datatype: 'json',
	      	data: position,
	      	 success: function(data, textStatus, request){
			
			if(data.status==null) {
				position.country=data.countryCode;
				callGetCountryNumber(position);
			} else alert("Elija una ubicación en tierra firme pertenciente a su país");
	      	 },
	           error: function (jqXHR, textStatus,  errorThrown) { alert("Login failed " + textStatus + errorThrown)},
	      	 async:   true
	          });	
	

}


function callGetCountryNumber(position) {


	doAjax({
	      	 url:  'http://api.geonames.org/countryInfoJSON',
	      	type: 'POST',
	      	datatype: 'json',
	      	data: position,
	      	 success: function(data, textStatus, request){
			position.countryNumber=data.geonames[0].isoNumeric;
			callGetNFm(position);
	      	 },
	           error: function (jqXHR, textStatus,  errorThrown) { alert("Login failed " + textStatus + errorThrown)},
	      	 async:   true
	          });	
	
}

function readyInit() {
	

	try {
	 if(google) googleOn=true;
	} catch (err) {
	 googleOn=false;
	}
	
	$('.ui-icon').addClass('ui-icon-alt');
	
	$.ajaxSetup({ timeout: 30000, 
				  error: function(jqXHR, textStatus,  errorThrown) {
					  if(textStatus=="error" || textStatus=="timeout")
						  alert("Tiene problemas con la conexión [" + errorThrown + "]");
				  },
//				  complete: function(xhr,textStatus) {
////					   if (xhr.status == "302") {
////						      alert(xhr.getResponseHeader("Location"));
////					   }
//					   var all=xhr.getAllResponseHeaders();
//					   if (xhr.status == 200) {
//						      var cType=xhr.getResponseHeader("Content-Type");
//
//						      if(cType.toLowerCase().indexOf("text/html")>=0 && 
//						    		  xhr.responseText.toLowerCase().indexOf("login")>=0) {						    	  
//						    	  if(!jf) window.location.reload();
//						      }
//					   }
//					  
//				  },
				  
//				  statusCode: {
//					302: function(xhr) {
//						alert(xhr.getResponseHeader("Location"));
//					}  
//				  },
//				  
				  type: 'POST',
//				  username: 'user',
//				  password: 'user01'
	});


	if(googleOn) geocoder = new google.maps.Geocoder();
	//else alert("No es posible acceder a google maps");


    $(document).one("mobileinit", function () {
        $.mobile.pageContainer = $('#bodycontainer');
        $.mobile.defaultPageTransition = 'none';
    });
    
    
    
   

    
    
	$("#onButton").bind("configReady", function(){
		configReady=true;
		if(configReady && activitiesReady) {
			setConfig();
		}
	 });
	
	$("#onButton").bind("activitiesReady", function(){
		activitiesReady=true;
		if(configReady && activitiesReady) {
			setConfig();
		}
	 });





	
	
	
//	$('.pageTab').bind('touchstart', function(e) {
//	    var pageto=$(this).attr("pageTo"); 
//		if(pageto && pageto!=null && pageto!="") goPage(pageto);
//	});	
//	
//	
//	if(!jf) {
//		$('.pageTab').bind('click', function(e) {
//		    var pageto=$(this).attr("pageTo"); 
//			if(pageto &&  pageto!=null && pageto!="") goPage(pageto);
//		});	
//	}
	
	
	//$("#backButton").toggle();
	//$("#version").toggle();
	//$("#onButton").hide();
	//$("#offButton").hide();
	
	$("#onButton").bind("loginReady", function(){
		getComboActivities();
	 });
	
	$("#onButton").bind("loginReady", function(){

		getPosition();
	});
	

    getLoginInfo();
    
    


	
//jf.setData("sample test");
	$(':jqmData(role=footer)').fixedtoolbar( { tapToggle: false } );

	setDictionary();



	
//	$("#backButton").click(function() { 
//		doRefreshTimeout();
//	});
	
	
	$("#sendChat").click(function() { 
		
		sendReceiveChat();

	});

	$("#receiveChat").click(function() { 
		
		sendReceiveChat();
		lastPeticionId=-1;
		$(".conversation blockquote").remove();
		$(".chatDates").remove();
		getChat();

	});

$("#aceptarEvento").click(function() { 
	aceptarEvento();

});


$("#cancelarEvento").click(function() { 

	$.mobile.changePage($('#page1'));
	
});



$("#onButton").click(onFunction);
	

function onFunction() {
	$("#onButton").fadeToggle(1500);
	
	onBtn();
	//setTimeout(onBtn,500);

	
	$.mobile.changePage($('#page1')); 
	
	$("#onButton").fadeToggle(3000);	
}


//$("#offButton").click(function() { 
//	
//	$("#offButton").toggle();
//	//jf.setData("off");
//	
//	$("#textinput1").removeAttr("disabled"); 
//	$("#selectmenu1").removeAttr("disabled");
//	$("#textinput2").removeAttr("disabled");
//	
////	clearInterval(watchID);
////	clearInterval(peopleWatchID);
//	clearTimeout(watchID);
//	clearTimeout(peopleWatchID);
//
//	navigator.geolocation.clearWatch(watchGPS);
//	//navigator.geolocation.clearWatch(watchID);		
//	clearOverlays();
//	watchID="OFF";
//	
//	
//	$("#onButton").fadeToggle(1500);
//});



/*$("#toggleswitch1").change(function() { 
	
 
//	if($(this).val()=="on" && watchID=="OFF") {
//		watchID = navigator.geolocation.watchPosition(onSuccess, onError, { timeout: 10000, enableHighAccuracy: true  }); 
//	} else if($(this).val()=="off" && watchID!="OFF") {
//		navigator.geolocation.clearWatch(watchID);
//		watchID="OFF";
//	} else { alert("none");}
	
	
	if($(this).val()=="on" && watchID=="OFF") {


		$("#textinput1").attr('disabled','disabled');
		$("#selectmenu1").attr('disabled','disabled');
		$("#textinput2").attr('disabled','disabled');

		//if(deviceId<0) {
		//if(config==null) {
		
			var d=new Date();
			var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
			
		    doAjax({
			 url:  getUrl() +  'config',
			data:{ deviceId: deviceId, activity: $(selectmenu1).val(), nick : $(textinput1).val(), comment: $(textinput2).val(), color : 'FFFF00'	, abbr: '', latency: '60000', refresh: '30000', mode: 'test', df: df},
			 success: function(result) {
				      deviceId=result.deviceId;
				      config=result;
				  },
			 async:   false
		    });

		//}
		
		locate(true);

	
		//watchID = navigator.geolocation.watchPosition(onSuccess, onError, {frequency: 30000, enableHighAccuracy: true  }); 
		watchID = setInterval(function(){locate(false)},config.latency); 
		peopleWatchID=setInterval(function(){getPeople()},config.refresh);

		//	clearTimeout(watchID);
		//	clearTimeout(peopleWatchID);
			
//		watchID = setTimeout(function(){locate(false)},120000); 
//		peopleWatchID=setTimeout(function(){getPeople()},20000);



	} else if($(this).val()=="off" && watchID!="OFF") {
		clearInterval(watchID);
		clearInterval(peopleWatchID);
//		clearTimeout(watchID);
//		clearTimeout(peopleWatchID);

		navigator.geolocation.clearWatch(watchGPS);
		//navigator.geolocation.clearWatch(watchID);		
		clearOverlays();
		watchID="OFF";
		$("#textinput1").removeAttr("disabled");
		$("#selectmenu1").removeAttr("disabled");
		$("#textinput2").removeAttr("disabled");	
	} else { alert("Desliza con suavidad o pulsa ligeramente");}	
	
});*/

	
//$('input[type="true"]').keypress( function () {
//	  alert("change");
//});


$("#page4").on("taphold","div",  function(event) {

	
	
	if(chatId.indexOf("__")>-1) {
		goPage("pageIntegrantes",true);
		showIntegrantes(true);
	}

	event.stopPropagation();
	
	
});

$("#idColSet").on("taphold","ul li",  function() {
	 

	
	if(navigator && navigator.notification) navigator.notification.vibrate(300);
	
	lat=$(this).attr('lat');
	lon=$(this).attr('lon');
	zoom=parseInt($(this).attr('zoom'));

	chatIdAux=$(this).attr('chatId');
	chatNickAux=$(this).find("h2").text();

	if(chatIdAux=="__activity") {
		chatIdAux=chatIdAux + "_" + $(selectmenu1).val();
		chatNickAux=$('#selectmenu1').find('option:selected').text();
	}
	
//	map.setZoom(parseInt(zoom));
//	map.setCenter(new google.maps.LatLng(lat,lon));
//	
	
	//jf.setData(chatNick);
	
	$.mobile.changePage('#uploadOptions',{transition: 'pop',role: 'dialog'});
	

});




$("#idColSet2").on("taphold","ul li",  function() {

	chatIdAux=$(this).attr('chatId');
	chatNickAux=$(this).find("h2").text();

	latAux=$(this).attr('lat');
	lonAux=$(this).attr('lon');
	zoomAux=parseInt($(this).attr('zoom'));

	$.mobile.changePage('#contactOptions',{transition: 'pop',role: 'dialog'});

});

$("#idColSet2").on("click","ul li",  function() {
	 
	if(!labelClick) {

		chatIdAux=$(this).attr('chatId');
		chatNickAux=$(this).find("h2").text();
	
		//if(chatId=="__activity") chatId=chatId + "_" + $(selectmenu1).val();
	
		goPage('page4',true);
		
	} else labelClick=false;
});


$("#idActivities").on("click","ul li",  function() {
	 
	var actId=$(this).attr('activityId');
	
	$('#selectmenu1').val(actId);	
	$('#selectmenu1').selectmenu();	
	$('#selectmenu1').selectmenu('refresh', true);
	
	getConfig();
	
});



$("#idColSet :not(#buscarTodos)").on("click", "ul li", function() {
 
	
	
	lat=$(this).attr('lat');
	lon=$(this).attr('lon');

	zoom=parseInt($(this).attr('zoom'));

	if(lat==null || lon==null || lat=="" || lon=="")  {
		zoom=2;
		lat=0.0000001;
		lon=0.0000001;
	}

	//$.mobile.changePage($('#page1')); 

	idSeguimiento=$(this).attr('chatId');
	
//	$(map_canvas).width(mapW);
//	$(map_canvas).height(mapH);
//	
	//google.maps.event.trigger(map, 'resize');
	//map.setZoom(parseInt(zoom));
	//map.setCenter(new google.maps.LatLng(lat,lon));
	
    goMap();

	//map.setUIToDefault();
});

$("#idColSet2").on("click","label",function(event) {
	event.stopPropagation();
	labelClick=true;
});

$("#idColSet2").on("click",".custom",function(event) {
	labelClick=true;
	event.stopPropagation();
});

$(".version").bind("click", function() {
	//idSeguimiento=null;
	
	if($.mobile.activePage.is("#page2")) {
		getPeople(true);
		refreshMap();
	} else if($.mobile.activePage.is("#page1")) {
		getPeople(false);
	}  else if($.mobile.activePage.is("#page4")) {
		getChat();
	} else if($.mobile.activePage.is("#pageContactos")) {
		showContacts(true);
	}  else if($.mobile.activePage.is("#pageActivities")) {
		showActivities();
	}  else if($.mobile.activePage.is("#pageIntegrantes")) {
		showIntegrantes(true);
} 	
	


});



//$( function() {
//$('body').bind( 'swipeleft', function( e ) {
//	
//$.mobile.changePage($('#page2'), 'slide');
//e.stopImmediatePropagation();
//return false;
//} );
//
//});

/*$('body').bind( 'swiperight', function( e ) {
$.mobile.changePage($('#page1'), 'slide');
e.stopImmediatePropagation();
return false;
} );

$("a").on("click", ".mylink", function() {  
alert(this.html());
});
*/


$("#page1").one("pageshow", function() {
	
	//$("#backButton").toggle();
	//$("#version").toggle();
	currPage="#page1";

});

$("#page2").on("pageshow", function() {
	//curPage=true;
	currPage="#page2";
	//if(!map || map==null) initMap();
	//postGoPage("page2");
	getPeople(true);
	refreshMap();
	
});

$("#page1").on("pageshow", function() {
	currPage="#page1";
	getPeople(false);
	//curPage=true;
	//postGoPage("page1");
});

$("#pageActivities").on("pageshow", function() {
	currPage="#pageActivities";
	showActivities();
});


//$("#page10").on("pageshow", function() {
//	//postGoPage("page10");
//	//curPage=true;
//});

$("#page4").on("pageshow", function() {
	currPage="#page4";
	//doChat();
	//curPage=true;
	//postGoPage("page4");

	getChat();  	
});


$("#pageContactos").on("pageshow", function() {
	currPage="#pageContactos";
	//showContacts(); 	
});

$("#pageIntervinientes").on("pageshow", function() {
	currPage="#pageIntervinientes";
	//showContacts(); 	
});

$("#pageActivities").on("pageshow", function() {
	currPage="#pageActivities";
	//showContacts(); 	
});



$("#page1").on("pagebeforehide", function() {
	//clearTimeout(peopleWatchID);
});

$("#page2").on("pagebeforehide", function() {
	//clearTimeout(peopleWatchID);
});

$("#page4").on("pagebeforehide", function() {
	clearTimeout(watchChat);
	//setChatLeido();
});

$("#pageContactos").on("pagebeforehide", function() {

});


$(window).resize(function() {
	
	mapW = $(window).width();
	mapH = $(window).height();
	
	$(map_canvas).width(mapW);
	$(map_canvas).height(mapH);

	
});

mapW = $(window).width();
mapH = $(window).height();


if(map && map!=null) {
	$(map_canvas).width(mapW);
	$(map_canvas).height(mapH);
}






//chatScroll = new iScroll('idConvContent');

//chatScroll = new iScroll('idConvContent',{
//	snap: 'blockquote'});

$("#idConvContent").niceScroll();
//$("#scrollContainer").niceScroll();

//alert($("#idConvContent").css("height"));


//$("#idConvContent").tinyscrollbar();
//var h=Math.max(parseInt($("#idConvContent").css("height"))/4,150);


//var h=parseInt($(window).height()/100);
//$("#chatBox").css("margin-bottom",h*4);


//$("#idConvContent").css("height",parseInt($(window).height()) - 210);



//alert($("#idConvContent").css("height"));

$("#idConvContent").scroll(function() {
	
	   scrollBottom=false;
	
   	//$('#log').append("onscroll:" + $("#idConvContent").scrollTop() + ", " + $('#idConvContent').get(0).scrollHeight + ", " + $("#idConvContent").height());
    
	   //$("#idConvContent").height
	   if($("#idConvContent").scrollTop() > $('#idConvContent').get(0).scrollHeight  - $("#idConvContent").height() * 2) {
		//if($("#idConvContent").scrollTop() > $('#idConvContent').get(0).scrollHeight - 100) {
	       scrollBottom=true;
	       
	   }
//	   else {
//		   scrollBottom=false; //
//	   }
});


var buscaFn=function( text, searchString ) {
$('#idColSet input[data-type="search"]').val(searchString);
return text.toLowerCase().indexOf( searchString ) === -1;
};


//
//if ($("#botones").hasClass('ui-listview')) {
//$("#botones").listview().listview("refresh");
//} else {
//$("#botones").trigger("create");
//$("#botones").listview();
//}
//$("#botones").listview( 'option', 'filterCallback', buscaFn );
//
//if ($("#botonesImprecisos").hasClass('ui-listview')) {
//$("#botonesImprecisos").listview().listview("refresh");
//} else {
//$("#botonesImprecisos").trigger("create");
//$("#botonesImprecisos").listview();
//}
//$("#botonesImprecisos").listview( 'option', 'filterCallback', buscaFn );
//
//if ($("#botonesSinPosicion").hasClass('ui-listview')) {
//$("#botonesSinPosicion").listview().listview("refresh");
//} else {
//$("#botonesSinPosicion").trigger("create");
//$("#botonesSinPosicion").listview();
//}
//$("#botonesSinPosicion").listview( 'option', 'filterCallback', buscaFn );
//
//


}





//});


function cargandoListados() {
	
    $("#botones li").remove();
    $("#botones").append('<li class="botones">cargando...</li>');
    $("#botones").listview("refresh");
    
    $("#botonesImprecisos li").remove();
    $("#botonesImprecisos").append('<li class="botones">cargando...</li>');
    $("#botonesImprecisos").listview("refresh");	
    
    $("#botonesSinPosicion li").remove();
    $("#botonesSinPosicion").append('<li class="botones">cargando...</li>');
    $("#botonesSinPosicion").listview("refresh");


    $("#botonesEventos li").remove();
    $("#botonesEventos").append('<li class="botones">cargando...</li>');
    $("#botonesEventos").listview("refresh");

}

function onBtn() {

	//$("#textinput1").attr('disabled','disabled');
	//$("#selectmenu1").attr('disabled','disabled');
	//$("#textinput2").attr('disabled','disabled');

	//if(deviceId<0) {
	//if(config==null) {
	
	getConfig();
	if(jf) mapContacts();

	//locate(true);


	
	//watchID = navigator.geolocation.watchPosition(onSuccess, onError, {frequency: 30000, enableHighAccuracy: true  }); 
//	watchID = setInterval(function(){locate(false)},config.latency); 
//	peopleWatchID=setInterval(function(){getPeople()},config.refresh);
	
	//watchID = setTimeout(function(){locate(false)},config.latency); 


	    //getPeople();
	    

//peopleWatchID=setTimeout(function(){getPeople()},config.refresh);
	
}

function getConfig() {
	var d=new Date();
	

	
    doAjax({
	 url:  getUrl() +  'config',
	type: 'POST',
  	datatype: 'json',
	data:{ 	deviceId: deviceId, 
			activity: $(selectmenu1).val(), 
			nick : $(textinput1).val(), 
			comment: $(textinput2).val(), 
			color : 'FFFF00'	,
			abbr: '', 
			latency: parseInt($("#latency").val()) * 60000, 
			refresh: parseInt($("#refresh").val()) * 1000, 
			mode: '0.1.11', 
			radio: $("#radio").val(), 	
			telefono: $("#telefono").val(),
			df: d.getTime()
		},
	 success: function(result) {

		      deviceId=result.deviceId;
		      config=result;
		      lat=config.lat;
		      lon=config.lon;
		     // alert(config.latency);
		      if(jf) jf.setData(config.latency);
		  		
		      $('#page1_fullExtent').text($.i18n._('page1_fullExtent2',[$('#selectmenu1 option:selected').text()]));
		  	
		      if(config.lat=="0" && config.lon=="0" && config.gpsPrecision=="-1") {
		    	  showAlert("Aviso",$.i18n._('no_position'));
		    	  //salirApp();
//		    	  config.lat="37.88";
//		    	  config.lon="-4.781";
		      }
		      
		      //zoom=12;
//		      lat=config.lat;
//		      lon=config.lon;
		      
		      $("#buscarTodos li.mapAll").attr("lat",lat);
		      $("#buscarTodos li.mapAll").attr("lon",lon);
		      $("#buscarTodos li.mapAll").attr("zoom",zoom);
		      
		      
		      
		  },
     error: function () { alert("No se ha podido acceder a la configuración. Reinténtelo de nuevo.")},
	 async:   true
    });
}

function salirApp() {
	if(navigator && navigator.app) navigator.app.exitApp();
}

function getInit(lon,lat,acu,calle,barrio,distrito,poblacion,provincia,region,pais,cp) {
	

	
	var d=new Date();
	
	var idAux=deviceId;
	var nombre="Newbie";
	var desc="Soy nuevo en ésto hasta que cambie mi nombre";
	var ini=d.getTime();
    var end=d.getTime();

	if(createEvent) {
		idAux="__event__"  + deviceId + "__" + d.getTime();
		nombre=$("#event_title").val();
		desc=$("#event_desc").val();
		//ini=(new Date(Date.parse($("#event_ini").val()))).format("dd/MM/yyyy  HH:mm");
		ini=Date.parseString($("#event_ini").val(),"dd/MM/yyyy HH:mm").getTime();
		end=Date.parseString($("#event_fin").val(),"dd/MM/yyyy HH:mm").getTime();


		//end=(new Date(Date.parse($("#event_fin").val()))).format("dd/MM/yyyy  HH:mm");;		
	}
		
    doAjax({
	 url:  getUrl() +  'init',
	 type: 'POST',
   	 datatype: 'json',
	 data:{ deviceId: idAux,
		 	lon: lon,
		 	lat: lat,
		 	precision: acu,
		 	calle: calle,
		 	barrio: barrio,
		 	distrito: distrito,
		 	poblacion: poblacion,
		 	provincia: provincia,
		 	region: region,
		 	pais: pais,
		 	nombre: nombre,
		 	desc: desc,
		 	ini: ini,
		 	end: end,
		 	codigoPostal: cp,
		 	time: d.getTime()
		},
	 success: function(result) {
			 if(!createEvent) {
				 deviceId=result.deviceId;
			 
				 config=result;
				 //$("#onButton").trigger("configReady");
				 configReady=true;

			 	 if(activitiesReady) setConfig();

			      lat=config.lat;
			      lon=config.lon;
			      
			      $("#buscarTodos li.mapAll").attr("lat",lat);
			      $("#buscarTodos li.mapAll").attr("lon",lon);
			      $("#buscarTodos li.mapAll").attr("zoom",zoom);
				 
				 
				 if(jf) jf.setData(config.latency);
			 } else {
				
				creteEvent=false;
				chatIdAux=idAux;
				chatNickAux=nombre;
				setSeguimiento(idAux, nombre, -1);				
				goPage('page4',true);
				 //$.mobile.changePage($('#page1')); 
			 }
			 
		  },
	 error: function( jqXHR, textStatus,  errorThrown ) {
			if(!createEvent) showAlert("Aviso",$.i18n._('no_config') + " (" + errorThrown+": "+textStatus + ")");
			else  alert("Error al crear evento");
			
	  },		  
	 async:   true
    });


}

function refreshMap() { 
	
	if(map && map!=null) {
		$(map_canvas).width(mapW);
		$(map_canvas).height(mapH);
	
		google.maps.event.trigger(map, 'resize');
		map.setZoom(parseInt(zoom));
		map.setCenter(new google.maps.LatLng(lat,lon));
	}

}

var idSeguimiento=null;

function setSeguimiento(id, title, index) {

	//doRefreshTimeout();	
	
	if(id.indexOf("__event")==-1) {
		idSeguimiento=id;
		if(index>-1) markersArray[index]['infowindow'].close();
		showAlert("Seguimiento", "Mapa en modo seguimiento a " + title);
		refreshTimeout=false;
		getPeople(true);
	} else {



		sendPeticion(
			{ 
			    remiteId : deviceId, 
				destinoId : id,
				texto: '__11',
				confirmar: true,
			},
			function() {
				showAlert("Evento", "Quedas apuntado al evento '" + title + "'");			
			}
		);


	}
	
}	
	
function joinRequest(id, title) {

	if(id.indexOf("__event")==-1) {
		if(id==deviceId) {
			showAlert("Buscando", "Eres tú");
			return;
		}
					
		doRefreshTimeout();

		idSeguimiento=id;

		sendPeticion(
			{ 
			      	remiteId : deviceId, 
				destinoId : id,
				texto: '__0',
				confirmar: true,
			},
			function() {
				showAlert("Buscando", "Enviada petición de búsqueda a " + title);			
			}
		);	
	
		//markersArray[id]['infowindow'].close(); 

	} else {

		if(jf && !jf.getGpsStatus()) alert("Active el gps para empezar a mandar posiciones");
		
		if(jf) jf.setData(0);
		
		sendPeticion(
			{ 
			    remiteId : deviceId, 
				destinoId : id,
				texto: '__12',
				confirmar: true,
			},
			function() {				
				showAlert("Evento", "Te has unido activamente al evento '" + title + "'");
				
			}
		);	

	}

}

var showingPeticion=false;

function getMarkers(people, paint) {

    var marker, i;

    var circle;
	var peticiones=false; 
    
	if(people!=null) {
    for (i = 0; i < people.length; i++) {  


    	//if(people[i].lat==null || people[i].lon==null || people[i].gpsPrecision==null || people[i].gpsPrecision=="-1" ||  people[i].gpsPrecision=="0") continue;// || parseFloat(people[i].gpsPrecision)> 1000) continue;

    	if(people[i].comment==null || people[i].comment=="") people[i].comment=$.i18n._('no_comment');  	

   
    	if(!showingPeticion && !peticiones && people[i].deviceId==deviceId && people[i].peticiones) {
    		
    		showingPeticion=true;
    		peticiones=true;
    		
    		var d=new Date();
    		var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

		doAjax({ 
		  url: getUrl() + "getPeticiones", 
		  dataType: 'json', 
		  data: { deviceId: deviceId, time: df}, 
		  success: function(data){ 	
    			
    			peticiones=data;
    		
    			if(peticiones!=null  && peticiones[0]!=null) {
    				showPeticion(peticiones);
    			} else {
    				showingPeticion=false;
    			}
		  }
//		  ,  
//		  error: function(jqXHR, status, errorThrown){  
//
//		  } 
		}); 
    		
    		/*$.getJSON(getUrl() + "getPeticiones?deviceId=" + deviceId + "&df=" + df, function(data){ 	
    			
    			peticiones=data;
    		
    			if(peticiones!=null  && peticiones[0]!=null) {
    				showPeticion(peticiones);
    			} else {
    				showingPeticion=false;
    			}
    		});*/
    	}

		var offset= (new Date().getTime() - parseFloat(people[i].online));
		var offsetPos= (new Date().getTime() - parseFloat(people[i].hora));
		
    	if(paint && !(people[i].lat==null || people[i].lon==null || people[i].gpsPrecision==null || people[i].gpsPrecision=="-1" 
    		||  people[i].gpsPrecision=="0") && (offsetPos <  1*3600000 || (offsetPos < 3 * 3600000 && offset < 3600000 )) ) {

    		
		var icon;

		if(people[i].deviceId.indexOf("__event")==-1) {
			 icon= {
			    path: google.maps.SymbolPath.CIRCLE,
			    scale: 3,
			    strokeColor: getPrecisionColor(people[i].gpsPrecision, offsetPos)
			};
		} else {
	    	 	icon= "http://www.googlemapsmarkers.com/v1/" + people[i].abbr + "/" + people[i].color + "/" + getContrast(people[i].color) + "/000000";
		}    		
    		
		      marker = new google.maps.Marker({
		    	  id: people[i].deviceId,
		        position: new google.maps.LatLng(people[i].lat, people[i].lon),
			icon: icon,        
		//	  icon: {
		//	    path: google.maps.SymbolPath.CIRCLE,
		//	    scale: 3,
		//	    strokeColor: getPrecisionColor(people[i].gpsPrecision, offsetPos)
		//	  },
			map: map,
			index: markersArray.length,
			precision: people[i].gpsPrecision,
			offset: offsetPos,
			color: people[i].color,
//			draggable: true,
			title: people[i].nick	
		      });
		     
		      

		      
		    	if(people[i].gpsPrecision<200) {
				      circle = new google.maps.Circle({
				    	  map: map,
				    	  radius: parseInt(people[i].gpsPrecision),
				    	  fillColor: '#F5FAFF',
				    	  strokeWeight: 1,
				    	  strokeColor: '#DCE1E6',
				    	  fillOpacity: 0.3
				    	});
		    		
		    		circle.bindTo('center', marker, 'position');
					circlesArray.push(circle);

		    	}
		    	

		var img=people[i].photoUrl;//"images/group.png";

		      var offset= (new Date().getTime() - parseFloat(people[i].hora));
		
		      
		      var latencia='<div style="color:black;">y latencia ' + parseInt(people[i].latency)/60000  +  ' min.</div>';
		      if(!people[i].gpsStatus) {
		    	  latencia='<div style="color:black;">con el gps apagado actualmente</div>';
		      }
		      
			marker['infowindow'] = new google.maps.InfoWindow({
		            content: 
				'<img style="padding: 20px; height: 64px; width: 64px;" src="' + img + '"/>' + 
			    '<div style="color:black;">' + marker.title +  ' ('+ people[i].comment + ')</div>' +
		            '<div style="color:black;">última posición ' + $.i18n._('time_ago', [msToDHM(offset)] ) +  '</div>' +	         
		            '<div style="color:black;">con precisión de ' + parseInt(people[i].gpsPrecision) +  ' m.</div>' +
		            latencia +		            
		            '<div style="color:black;">' + 
		            '<a href=""  onclick="setSeguimiento(\'' + marker.id + '\',\'' + marker.title + '\' ,\'' + marker.index + '\');"><img  src="images/map.png"/></a>' + 
		            '<a href=""  onclick="joinRequest(\'' + marker.id + '\',\'' + marker.title + '\' );"><img  src="images/goto.png"/></a>' + 
		            '<a href=""  onclick="goChat(\'' + marker.id + '\',\'' + marker.title + '\' );"><img  src="images/chat.png"/></a>' + 	            
		            '</div>' +
		            '<div style="color:black;"><input onfocus="msgfocus()" onblur="msgblur()" type="text" id="' + deviceId + 'MsgFrom"/><a href="" onclick="setMessage(\'' + marker.id + '\',\'' + marker.title + '\' );"><img class="mylink" src="images/mail2_send.png"/></a></div>'
			    //
		            
		
		        });
			
			if(people[i].deviceId.indexOf("__event")==-1) {
				addMarker(marker);
				
			} else {
				// img=people[i].photoUrl;//"https://com-ficv-findme.googlecode.com/svn/wiki/img/photo.png";
  
				marker['infowindow'] = new google.maps.InfoWindow({
				    content: 			'<img style="padding: 20px; height: 64px; width: 64px;" src="' + img + '"/>' + 
					'<div style="color:black;">' + marker.title +  ' ('+ people[i].comment + ')</div>' +
				    '<div style="color:black;">comienza a las ' + printHora(people[i].online) + ' el día ' + printEventDate(people[i].online) +  '</div>' +	         
				    '<div style="color:black;">' + 
				    '<a href=""  onclick="setSeguimiento(\'' + marker.id + '\',\'' + marker.title + '\' ,\'' + marker.index + '\');"><img  src="images/map.png"/></a>' + 
				    '<a href=""  onclick="joinRequest(\'' + marker.id + '\',\'' + marker.title + '\' );"><img  src="images/goto.png"/></a>' + 
				    '<a href=""  onclick="goChat(\'' + marker.id + '\',\'' + marker.title + '\' );"><img  src="images/chat.png"/></a>' + 	            
				    '</div>' +
				    '<div style="color:black;"><input onfocus="msgfocus()" onblur="msgblur()" type="text" id="' + deviceId + 'MsgFrom"/><a href="" onclick="setMessage(\'' + marker.id + '\',\'' + marker.title + '\' );"><img class="mylink" src="images/mail2_send.png"/></a></div>'
				    //
				    
		
		        });
			}

		    
			google.maps.event.addListener(marker, 'click', function() {
				refreshTimeout=true; 
				clearTimeout(peopleWatchID);
				this['infowindow'].open(map, this);				
				
				refreshTimeout=false;
				peopleWatchID=setTimeout(function(){getPeople(true)},12000);
				 
				
			});
		
			google.maps.event.addListener(marker['infowindow'],'closeclick',function(){
		
				doRefreshTimeout();
				labelsArray[this.labelIndex].open();
			});
			
			markersArray.push(marker);
	
			
    	}	
			
    	
	    //setTimeout(geocoderTimer, i*1000,new google.maps.LatLng(people[i].lat, people[i].lon),people[i].deviceId);
	       
		var img=people[i].photoUrl;
		//if(people[i].deviceId.indexOf("__event")>-1) img=people[i].photoUrl;//"https://com-ficv-findme.googlecode.com/svn/wiki/img/photo.png";
  

		var userdata='<li class="botones" chatId="' + people[i].deviceId + '" lat="' + people[i].lat +'" lon="' + people[i].lon + '" zoom="17" data-theme="c"><a href=""  data-transition="none">' + 	
		        '<h2>' + people[i].nick + '</h2>' +
		        '<img style="padding: 20px; height: 64px; width: 64px;" src="' + img + '">' +
		        '<p><span id="calle' + people[i].deviceId + '">' + people[i].calle + '</span></p>' +
		        '<p><strong><span id="barrio' + people[i].deviceId + '">' + people[i].barrio + ' / ' + people[i].distrito + '</span></strong></p>' +
		        '<p><span id="poblacion' + people[i].deviceId + '">' + people[i].codigoPostal + ' - ' + people[i].poblacion  + '</span></p>';
		if(people[i].deviceId.indexOf("__event")>-1) {
		     userdata=userdata + 
		     '<p>' + people[i].comment + ' (' + printHora(people[i].online) + ')</p>' +
		     '<p class="ui-li-aside"><strong> ' + printEventDate(people[i].online) + '</strong></p>';		     
		} else {
		     userdata=userdata + 
		     '<p>' + people[i].comment + ' (' + printHora(people[i].hora) + ')</p>' +
		     '<p class="ui-li-aside"><strong> ' + printHora(people[i].online) + '</strong></p>';
//		        '<p class="ui-li-aside"><strong> ' + $.i18n._('time_ago', [msToDHM(offset)]) + '</strong></p>' +				
		}		
		 userdata=userdata +  '</a></li>';
		        
		var userNoData='<li class="botones" chatId="' + people[i].deviceId + '" lat="' + people[i].lat +'" lon="' + people[i].lon + '" zoom="14" data-theme="c"><a href=""  data-transition="none">' + 
		
        '<h2>' + people[i].nick + '</h2>' +	  
        '<img style="padding: 20px" src="images/group.png">' +
        '<p>' + people[i].comment + '</p>' +
        '<p class="ui-li-aside"><strong>' + printHora(people[i].online) + '</strong></p>' +				
		'</a></li>'
		     


		if(people[i].deviceId.indexOf("__event")>-1) {	
			$("#botonesEventos").append(userdata);
		} else if(people[i].lat==null || people[i].lon==null || people[i].gpsPrecision==null || people[i].gpsPrecision=="-1" ||  people[i].gpsPrecision=="0"
				|| (offsetPos >  3*3600000) || (offsetPos >  1*3600000 && offset > 3600000 )) {
			$("#botonesSinPosicion").append(userNoData);
		} else if( people[i].gpsPrecision > 200 || offset > 3600000) {
			$("#botonesImprecisos").append(userdata);
		} else {
			$("#botones").append(userdata);
		}


		
	    if(idSeguimiento!=null && idSeguimiento==people[i].deviceId ) { 	

	    	lat=people[i].lat;
	        lon=people[i].lon;
	        //zoom=16;
	    	map.setZoom(parseInt(zoom));
	    	map.setCenter(new google.maps.LatLng(lat,lon));
	    	
	    	if(idSeguimiento!=deviceId) playDistanceSound(getDistancia(people[i],config));
    	
	    }
	
    
    }

	}


    if(paint) paintLabels();

    paint=false;
    
	

    
//	$('#botones').listview();
    $("#botones").listview("refresh",true); 	

//	$('#botonesImprecisos').listview();
    $("#botonesImprecisos").listview("refresh",true); 	    
	
    
//	$('#botonesSinPosicion').listview();
    $("#botonesSinPosicion").listview("refresh",true);

     $("#botonesEventos").listview("refresh",true);

 	      
    
    //$('input[data-type="search"]').trigger("keyup");
    $('#idColSet input[data-type="search"]').val("");
	
	//$("#scrollContainer").scrollview();
//    $("#scrollContainer").getNiceScroll().resize();
    
//	$('#scrollContainer').animate({
//	    scrollTop: $('#scrollContainer').get(0).scrollHeight
//	}, 1500);
}


function getDistancia(target, observer) {
	var lat2 = target.lat; 
	var lon2 = target.lon; 
	var lat1 = observer.lat; 
	var lon1 = observer.lon; 

	var R = 6371; // km 

	var x1 = lat2-lat1;
	var dLat = toRad(x1);  
	var x2 = lon2-lon1;
	var dLon = toRad(x2);  
	var a = Math.sin(dLat/2) * Math.sin(dLat/2) + 
	                Math.cos(toRad(lat1	)) * Math.cos(toRad(lat2)) * 
	                Math.sin(dLon/2) * Math.sin(dLon/2);  
	var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
	var d = R * c; 

	//alert(d*1000);
	return d*1000;	

}


function toRad(x) {
	   return x * Math.PI / 180;
}



function playDistanceSound(distancia) {
	var pitido='/android_asset/www/mp3/pitido.mp3';
	var pitido2='/android_asset/www/mp3/pitido2.mp3';
	var pitido3='/android_asset/www/mp3/pitido2.mp3';
	var pitido4='/android_asset/www/mp3/pitido4.mp3';
	var pitido5='/android_asset/www/mp3/pitido5.mp3';
	var pitido6='/android_asset/www/mp3/pitido6.mp3';
	var pitido7='/android_asset/www/mp3/pitido7.mp3';
	var pitido8='/android_asset/www/mp3/pitido8.mp3';
	var pitido9='/android_asset/www/mp3/pitido9.mp3';
	
	if(distancia<1000) playSound(pitido); 
	if(distancia<750) setTimeout(function(){playSound(pitido9);},250); 
	if(distancia<500) setTimeout(function(){playSound(pitido2);},500);
	if(distancia<250) setTimeout(function(){playSound(pitido3);},750);
	if(distancia<200) setTimeout(function(){playSound(pitido4);},1000);
	if(distancia<150) setTimeout(function(){playSound(pitido5);},250); 
	if(distancia<100) setTimeout(function(){playSound(pitido6);},500);
	if(distancia<75)  setTimeout(function(){playSound(pitido7);},750);
	if(distancia<50)  setTimeout(function(){playSound(pitido8);},1000);
	
	
}


function playSound(url) {
    // Play the audio file at url
    
	if(jf) {
		var my_media = new Media(url,
	
        // success callback
        function() {
            console.log("playAudio():Audio Success");
        },
        // error callback
        function(err) {
            console.log("playAudio():Audio Error: "+err);
        });

    // Play audio
		my_media.play();
	} 
//	var snd = new Audio(url); // buffers automatically when created
//	snd.play();
}



function geocoderTimer(latLng, id) {
	
	//alert("timing " + id);
	geocoder.geocode({'latLng': latLng}, makeGeocodeCallback(id));
	
}


function makeGeocodeCallback(id) {
    var geocodeCallBack = function(results, status) {
    	
    	
    	
		var dir="dirección no disponible";
		var calle="calle no disponible";
		var pob="población no disponible";
		
		if (status == google.maps.GeocoderStatus.OK) {

			   for(j=0;j<results.length;j++) {
				 
				   if(results[j].types[0]=="street_address") calle=results[j].address_components[1].short_name;
				   else if(results[j].types[0]=="neighborhood") dir=results[j].address_components[0].short_name + " / ";
				   else if(results[j].types[0]=="sublocality") dir= dir + results[j].address_components[0].short_name;
				   else if(results[j].types[0]=="postal_code") pob= results[j].address_components[0].short_name + " - " + results[j].address_components[1].short_name ;
					
			   
			   }
			
//			$('#barrio' + id).text(dir);
//			$('#calle' + id).text(calle);


		 } else {
			 calle=status;
		    //alert("Geocoder failed due to: " + status);
		 }
		if(calle==status) {
			calle=status;
		}
		
		$('#barrio' + id).text(dir);
		$('#calle' + id).text(calle);
		$('#poblacion' + id).text(pob);		
//		$("#botones").append('<li chatId="' + people.deviceId + '" lat="' + people.lat +'" lon="' + people.lon + '" zoom="17" data-theme="c"><a href=""  data-transition="none">' + 
//				
//		        '<h2>' + people.nick + '</h2>' +
//		        '<p><strong>' + dir + '</strong></p>' +
//		        '<p>' + people.comment+ '</p>' +
//		        '<p class="ui-li-aside"><strong>' + printHora(people.hora) + '</strong></p>' +				
//			
//				'</a></li>');
        
    }
    
    return geocodeCallBack;
}

var pause=false;

function onPause() {
  //alert("pause");
	
	pause=true;
	clearTimeout(peopleWatchID);
	clearTimeout(watchChat);	
}


function onResume() {
 


	
	if($.mobile.activePage.is("#page2")) {
		getPeople(true);
	} else if($.mobile.activePage.is("#page1")) {
		getPeople(false);
	}  else if($.mobile.activePage.is("#page4")) {
		getChat();
	}
}


var hayMsg=false;

function onNotification(hay) {

//	alert("onnoti: " + hay);
	
	if(hay && currPage!="#pageContactos") { 
		goPage("pageContactos",true);
	}

	//alert("noti " + hay);
	if(hay) showContacts();
	
//	alert("noti " + hay);
//	hayMsg=hay;
//	if(hayMsg || currPage==null) {
//		$.mobile.changePage($('#pageContactos'));
//		showContacts();
//	} else {
//		$.mobile.changePage($(currPage));
//	}
	
	
}


function onBackKeyDown() {
   // e.preventDefault();

	if($.mobile.activePage.is("#page4")) {
		$.mobile.changePage($('#pageContactos'));
	} else if($.mobile.activePage.is("#pageIntegrantes")) {
		$.mobile.changePage($('#page4'));
	}
	else {
		showConfirm();    
	}
}

function onMenuKeyDown(e) {
	//e.preventDefault();
//	if($.mobile.activePage.is("#page1"))
//		$.mobile.changePage($('#page2'), 'slide');
//	else if($.mobile.activePage.is("#page2"))
//		$.mobile.changePage($('#page4'), 'slide');
//	else 
//		$.mobile.changePage($('#page1'), 'slide');
	
	e.preventDefault();
	
//	if(chatId<0)  {
//		chatId="__activity"
//		chatNick="todos en " + $("#selectmenu1").val();
//	}
	
	$.mobile.changePage('#menu',{transition: 'pop',role: 'dialog'});
	
			
	clearTimeout(watchChat);
	doRefreshTimeout();
}


function getContrastYIQ(hexcolor){
	var r = parseInt(hexcolor.substr(0,2),16);
	var g = parseInt(hexcolor.substr(2,2),16);
	var b = parseInt(hexcolor.substr(4,2),16);
	var yiq = ((r*299)+(g*587)+(b*114))/1000;
	return (yiq >= 128) ? 'black' : 'white';
}

function getContrast(hexcolor){
	var r = parseInt(hexcolor.substr(0,2),16);
	var g = parseInt(hexcolor.substr(2,2),16);
	var b = parseInt(hexcolor.substr(4,2),16);
	var yiq = ((r*299)+(g*587)+(b*114))/1000;
	return (yiq >= 128) ? '000000' : 'FFFFFF';
}

function getRGBA(hexcolor){
	var r = parseInt(hexcolor.substr(0,2),16);
	var g = parseInt(hexcolor.substr(2,2),16);
	var b = parseInt(hexcolor.substr(4,2),16);
	return "rgba(" + r + "," + g + "," + b + ",0.2)";
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

function msOffset(v) {
	
	var offset= (new Date().getTime() - parseFloat(v));
	msToDHM(offset);
}


function printHora(v,prefix,sufix,idPet,idDev) {
	

	if(v==null && idPet && idDev && idDev!=deviceId &&
			chatId.indexOf("__activity")==-1 && chatId.indexOf("__event")==-1 &&  chatId.indexOf("__group")==-1) { 
		recibido(idPet);
	}
	
	var d=new Date();
	d.setTime(v);
	//var df= d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + ":" + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
	var result= (d.getHours()<10?"0":"") + d.getHours() + ":" + (d.getMinutes()<10?"0":"") + d.getMinutes();
	
	if(v==null) { result=""; prefix="";sufix="";}
	
	if(prefix==null) return result; 
	else  return prefix + result + sufix;

}

var lastDate=null;
function printDate(d) {
	var aux= new Date();
	
	aux.setTime(d);
//	var newDate	= "--> " + aux.getFullYear() + "-" + (aux.getMonth() + 1) + "-" + aux.getDate();
	var newDate = aux.getDate() + "-" + (aux.getMonth() + 1) + "-" + aux.getFullYear() ;
	if(lastDate==null || lastDate!=newDate) {
		lastDate=newDate;
		return newDate;
	}
	else return "";
}


function printEventDate(d) {
	var aux=new Date();
	aux.setTime(d);
	return aux.getDate() + "-" + (aux.getMonth() + 1) + "-" + aux.getFullYear() ; 
}


function msToDHM(v) {
	  var days = v / 8.64e7 | 0;
	  var hrs  = (v % 8.64e7)/ 3.6e6 | 0;
	  var mins = Math.round((v % 3.6e6) / 6e4);
	  //var secs = Math.round((v % 6e4) / 1e3);
	  
	  var result='';
	  if(days>0) result=result + days + 'd ';
	  if(hrs>0) result=result + hrs + 'h ';
	  if(mins>0) result=result + mins + '\' ';
	 // if(secs>0) result=result + secs + ' segundos ';
	  
	  if(result=='') result='segundos';
	  return result;
	  
	  //return days + ' días ' + z(hrs) + ' horas y ' + z(mins) + ' minutos';

	  //function z(n){return (n<10?'0':'')+n;}
}

function showConfirm() {
    navigator.notification.confirm(
        '¿Está seguro que desea salir de la aplicación?',  // message
        onConfirm,              // callback to invoke with index of button pressed
        'Salir',            // title
        'Dejar GPS de fondo,Salir y quitar GPS,Mantener abierta'          // buttonLabels
    );
}

function onConfirm(buttonIndex) {
	if(buttonIndex==1) salirApp();
	else if(buttonIndex==2)  { 
		//jf.stopService(); 
		jf.setData("-1");
		salirApp(); 
	}
}


function showPeticion(peticiones) {
	
	var msg=" dice: " + peticiones[0].texto;
	if(peticiones[0].texto=="__0") msg=" quiere ir a tu encuentro";
	else if(peticiones[0].texto=="__1") msg=" te espera";
	else if(peticiones[0].texto=="__2") msg=" no te puede esperar";
	else if(peticiones[0].texto=="__3") msg=" quiere que le sigas";
	
	
	
	var offset= (new Date().getTime() - parseFloat(peticiones[0].hora));
	msg = peticiones[0].remite.nick + msg + " (" + $.i18n._('time_ago', [msToDHM(offset)] ) + ")";

	
    if(navigator && navigator.notification) {
    	
    	if(peticiones[0].texto=="__0") 
		    	navigator.notification.confirm(
		         msg,
		        function(buttonIndex){
		        	onShowPeticion(buttonIndex, peticiones[0].id);
		        },              // callback to invoke with index of button pressed
		        'Petición de encuentro',            // title
		        'Te espero,Me voy ya,Mejor Sígueme'          // buttonLabels
		    );
    	
    	else  {
//    		navigator.notification.alert(msg, //mensaje
//    	
//    			function() {
//    				showingPeticion=false;
//    				respuesta(peticiones[0].id,"___");
//    			    				
//	    	}, //funcion callback
//	
//	    	"Mensaje", //título
//	
//	    	'Ok' // nombre del botón	
//	
//	    	);
    		
	    	navigator.notification.confirm(
			         msg,
			        function(buttonIndex){			
			        	 	showingPeticion=false;		        	 	
			        	 	if(buttonIndex!=0) respuesta(peticiones[0].id,"___");
		    				if(buttonIndex==2)  goChat(peticiones[0].remite.deviceId,peticiones[0].remite.nick);
			        },              // callback to invoke with index of button pressed
			        'Recepción',            // title
			        'Ok,Ir al chat'          // buttonLabels
			 );
    		

    	}
    }	
    
    else {
    	alert(msg);
    	showingPeticion=false;
    	if(peticiones[0].texto=="__0") respuesta(peticiones[0].id,"__1");
    	else  respuesta(peticiones[0].id,"___");
    }
    
    
}
    
function onShowPeticion(buttonIndex,id) {
	
	
	var resp="__0";
	if(buttonIndex==1) resp="__1";
	else if(buttonIndex==2)  resp="__2";
	else if(buttonIndex==3)  resp="__3";	
	
	showingPeticion=false;
	
	
	respuesta(id,resp);

}
    

function respuesta(id,resp) {
	
	var d=new Date();

    doAjax({
   	 url: getUrl() + 'setRespuesta',
   	 datatype: 'json',
   	 type: 'POST',
   	 data:{       id : id, 
			deviceId : deviceId,
				respuesta: resp,
			time: d.getTime()
   		  },
   	 success: function(result) {
 
   		  },
        error: function () { alert("No se ha podido enviar la respuesta");}

       });
// 	$.get(getUrl() + 'setRespuesta',
//		{       id : id, 
// 				deviceId : deviceId,
// 				respuesta: resp,
//				time: d.getTime()
//		}
// 	);

 	if(jf) jf.cleanNotification();
 	
}

function recibido(id) {
	
	var d=new Date();

 	$.post(getUrl() + 'setRecibido',
		{       id : id, 
				time: d.getTime()
		}
 	);

}


function setMessage(id, title) {

	var input=deviceId + 'MsgFrom';
	var msg = document.getElementById(input).value;
	document.getElementById(input).value="";
	doRefreshTimeout();
	
		sendPeticion(
			{ 
			      	remiteId : deviceId, 
				destinoId : id,
				texto: msg,
				confirmar: true,
			},
			function() {				
				showAlert("Mensaje", "Se ha enviado su mensaje a " + title);
			}
		);

	//$.mobile.changePage($('#page1')); 
}


function msgfocus() {
	refreshTimeout=true; 
	clearTimeout(peopleWatchID);

}


function msgblur() {	
	refreshTimeout=false;
	clearTimeout(peopleWatchID);
	//peopleWatchID=setTimeout(function(){getPeople(true)},12000);
}

function goChat(id,title) {
	chatIdAux=id;
	chatNickAux=title;
	goPage("page4",true);
}

function getComboActivities(doGetPosition) {
		$("#selectmenu1").load(getUrl() + "activities",function(responseTxt,statusTxt,xhr){
		    if(statusTxt=="success") {
		    	if(doGetPosition) getPosition();
		    	//$("#onButton").trigger("activitiesReady");

				 activitiesReady=true;
			 	 if(configReady) setConfig();
		    	//if(config!=null) {
		    		//setConfig();
		    	//}	    	
		    }
		    else if(statusTxt=="error")
				showAlert("¡Atención!",$.i18n._('no_config') + " (" + xhr.status+": "+xhr.statusText + ")");
		    	//salirApp();

		});
}

function querystring(key) {
	   var re=new RegExp('(?:\\?|&)'+key+'=(.*?)(?=&|$)','gi');
	   var r=[], m;
	   while ((m=re.exec(document.location.search)) != null) r[r.length]=m[1];
	   if(r.length>0 && (r[0]==null || r[0]=="undefined")) r=[];
	   return r;
}



function sendPeticion(data, successFunction) {

	var d=new Date();
	data.time=d.getTime();
		
	doAjax({
	      	 url:  getUrl() + 'setPeticion',
	      	type: 'POST',
	      	datatype: 'json',
	      	data: data,
	      	 success: function(data, textStatus, request){	
	      		 successFunction();
	      	 },
	           error: function (jqXHR, textStatus,  errorThrown) { alert("Fallo en envío de mensajes");},
	      	 async:   true
	          });			
		
}

function doAjax(params, depth) {

	if(!depth || depth==null) depth=0;
	if(depth==4) {
		alert("Imposible conectar con " + params.url);
		params.error();
	}
	$.ajax({
	 	 url:  params.url,
	 	type: params.type,
	 	datatype: params.datatype,
	 	data: params.data,
	 	 success: function(data,status,xhr) {
	 		 	    //alert("succes in " + params.url);
	 		 	//if (xhr.status == 200) {
					      var cType=xhr.getResponseHeader("Content-Type");

					      if(cType.toLowerCase().indexOf("text/html")>=0 && 
					    		  xhr.responseText.toLowerCase().indexOf("login")>=0) {						    	  
					    	  if(!jf) window.location.reload();
					    	  else {
					    		  getLoginInfo();
					    		  doAjax(params);
					    	  }
					      }
					      
					      else {
					    	  params.success(data,status,xhr);
					      }
				  // }	  
		 },

	      error: function (jqXHR, textStatus,  errorThrown)  { 
       	   //alert("Reintentando " + params.url);
           doAjax(params,depth+1);
           //alert(params.error);
    	  },
	 	 async:   true
     });
	
}


	
